package com.github.tvbox.osc.base

import android.content.Context
import androidx.multidex.MultiDexApplication
import com.github.tvbox.osc.callback.EmptyCallback
import com.github.tvbox.osc.callback.LoadingCallback
import com.github.tvbox.osc.data.AppDataManager
import com.github.tvbox.osc.server.ControlManager
import com.github.tvbox.osc.util.HawkConfig
import com.github.tvbox.osc.util.OkGoHelper
import com.github.tvbox.osc.util.PlayerHelper
import com.kingja.loadsir.core.LoadSir
import com.orhanobut.hawk.Hawk
import com.orhanobut.logger.Logger
import io.github.source.Init
import io.github.source.config.VodConfig
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.unit.Subunits

/**
 * @ClassName: AppKt
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: huangrongcai
 * @date: 2024/9/19
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
public class App : MultiDexApplication() {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        sinstance = this
    }
    override fun onCreate() {
        super.onCreate()
        sinstance = this
        Hawk.init(this).build()
        Thread(::onAsyncInit).start()

        //初始化数据库
        AppDataManager.init()
        LoadSir.beginBuilder()
            .addCallback(EmptyCallback())
            .addCallback(LoadingCallback())
            .commit()
        AutoSizeConfig.getInstance().setCustomFragment(true).unitsManager
            .setSupportDP(false)
            .setSupportSP(false).supportSubunits = Subunits.MM

    }

    private fun initParams() {
        // Hawk
        Hawk.put(HawkConfig.DEBUG_OPEN, false)
        if (!Hawk.contains(HawkConfig.PLAY_TYPE)) {
            Hawk.put(HawkConfig.PLAY_TYPE, 1)
        }
    }

    fun onAsyncInit() {
        // 使用协程处理异步初始化
        try {
            asyncInit()
        } catch (e: Exception) {
            // 处理异常
            Logger.e(e, "Error during async initialization: ${e.message}")
        } finally {
            println("Async initialization completed")
        }
    }

    private fun asyncInit() {
        ControlManager.init(this)
        // 异步初始化操作
        // 示例：模拟网络请求
        //异步加载
        initParams()
        // OKGo
        OkGoHelper.init()
        // 初始化Web服务器

        PlayerHelper.init()

    }

    fun onLazyInit() {
        //懒加载 需要时
    }

    fun onDelayInit() {
        //延时加载 某个时机（生命周期，初始完成）
    }

    companion object {
        var sinstance: App? = null

        @JvmStatic
        fun getInstance(): App? {
            return sinstance
        }
    }

}